/*
 * @Copyright: 2016 www.yyfax.com Inc. All rights reserved.
 */
package com.yyfax.pay.order.controller.api;

import javax.validation.Valid;

import com.yyfax.framework.common.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yyfax.commons.lang.DateUtil;
import com.yyfax.framework.model.EmptyContent;
import com.yyfax.framework.model.YYFaxRsp;
import com.yyfax.pay.common.annotation.CheckSign;
import com.yyfax.pay.common.enums.AuthStateEnum;
import com.yyfax.pay.common.enums.PayRspCodeEnum;
import com.yyfax.pay.common.model.to.YYPayApiReq2;
import com.yyfax.pay.config.data.service.MerchantConfigService;
import com.yyfax.pay.order.data.service.AuthOrderService;
import com.yyfax.pay.order.model.po.AuthOrderPO;
import com.yyfax.pay.order.model.to.AuthWithoutVerifyParams;
import com.yyfax.pay.order.model.to.auth.AuthWithoutVerifyDirectParams;
import com.yyfax.pay.order.service.AuthService;
import com.yyfax.pay.third.model.to.yyfax.WithoutVerifyYYContent;

/**
 * 独立鉴权入口
 *
 * @author buyi
 * @date 2017-04-18 14:32:51
 * @since v1.0.0
 */
@Controller
@RestController
public class AuthApiDirectController {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private MerchantConfigService merchantConfigService;

	@Autowired
	private AuthOrderService authOrderService;

	@Autowired
	private AuthService authService;

	// @CheckSign
	// @RequestMapping(method = RequestMethod.POST, path = "/api/auth/direct/send_verify")
	// public YYFaxRsp<VerifyCodeContent> directSendVerifyCode(@RequestBody @Valid YYPayApiReq2<AuthSendVerifyDirectParams> req) throws Throwable {
	// logger.debug("enter payOrder for api controller");
	//
	// // if (req == null || req.getParams() == null) {
	// // throw new YYException(RspCodeEnum.COMMON_ERROR_PARAMETER_INVALID);
	// // }
	//
	// AuthSendVerifyDirectParams params = req.getParams();
	//
	// // 1.校验参数
	// params.validate();
	//
	// // 2.验签
	// // MerchantConfigPO merchantConfigPO =
	// // merchantConfigService.queryByMerchantCode(params.getMerchantCode());
	// // if (merchantConfigPO == null) {
	// // throw new YYException(PayRspCodeEnum.PAY_CODE_MERCHANT_NOT_EXISTS,
	// // "无效商户：" + params.getMerchantCode());
	// // }
	// //
	// // req.checkSign(merchantConfigPO.getSignKey());
	//
	// // 持久订单信息
	// AuthOrderParams authOrderParams = new AuthOrderParams();
	// BeanUtils.copyProperties(params, authOrderParams);
	//
	// AuthOrderPO authOrderPO = authService.saveAuthOder(authOrderParams);
	//
	// SendAuthenticationVerifyCodeYYContent sendVerifyCodeYYContent = authService.sendVerifyCode(authOrderPO, params.getIdNo(), params.getName(),
	// params.getCardNo(), params.getPhone());
	//
	// VerifyCodeContent content = new VerifyCodeContent(sendVerifyCodeYYContent.getToken(), null);
	//
	// return new YYFaxRsp<VerifyCodeContent>(sendVerifyCodeYYContent.getResultCode(), sendVerifyCodeYYContent.getResultMsg(),
	// sendVerifyCodeYYContent.getResultMsg(), content);
	//
	// }
	//
	// @RequestMapping(method = RequestMethod.POST, path = "/api/auth/direct/confirm")
	// public YYFaxRsp<EmptyContent> directAuthConfirm(@RequestBody YYPayApiReq<AuthConfirmDirectParams> req) throws Throwable {
	//
	// if (req == null || req.getParams() == null) {
	// throw new YYException(RspCodeEnum.COMMON_ERROR_PARAMETER_INVALID);
	// }
	//
	// AuthConfirmDirectParams params = req.getParams();
	//
	// // 1.校验参数
	// params.validate();
	//
	// // 2.验签
	// MerchantConfigPO merchantConfigPO = merchantConfigService.queryByMerchantCode(params.getMerchantCode());
	// if (merchantConfigPO == null) {
	// throw new YYException(PayRspCodeEnum.PAY_CODE_MERCHANT_NOT_EXISTS, "无效商户：" + params.getMerchantCode());
	// }
	//
	// req.checkSign(merchantConfigPO.getSignKey());
	// // 获取订单信息
	// AuthOrderPO authOrderPO = authOrderService.queryByOrderIdAndMerchantCode(params.getOrderId(), params.getMerchantCode());
	// if (authOrderPO == null || !AuthStateEnum.DEALING.isValue(authOrderPO.getState())) {
	// return new YYFaxRsp<EmptyContent>(PayRspCodeEnum.COMMON_ERROR_BAD_REQUEST, "订单不存在/过期");
	// }
	//
	// // 判断订单是否过期
	// if (DateUtil.str2DateTime(authOrderPO.getExpireTime()).getTime() <= System.currentTimeMillis()) {
	// return new YYFaxRsp<EmptyContent>(PayRspCodeEnum.COMMON_ERROR_BAD_REQUEST, "订单不存在/过期");
	// }
	//
	// AuthenticationYYContent authenticationYYContent = authService.authentication(authOrderPO, params.getIdNo(), params.getName(),
	// params.getCardNo(), params.getPhone(), params.getToken(), params.getValidCode());
	//
	// // AuthConfirmDirectContent content = new AuthConfirmDirectContent();
	// // BeanUtils.copyProperties(authOrderPO, content);
	// // content.setResultCode(authenticationYYContent.getResultCode());
	// // content.setResultMsg(authenticationYYContent.getResultMsg());
	// return new YYFaxRsp<EmptyContent>(authenticationYYContent.getResultCode(), authenticationYYContent.getResultMsg(), null);
	// }

	/**
	 * 独立鉴权-直连
	 * 不需要验证码的鉴权
	 *
	 * @param req 请求参数
	 * @return
	 * @author xulqb
	 * @date 2017-12-21 10:10:04
	 * @since V1.0.0
	 */
	@CheckSign
	@RequestMapping(method = RequestMethod.POST, path = "/api/auth/direct/confirm_without_verify")
	public YYFaxRsp<WithoutVerifyYYContent> directAuthConfirmWithoutCodeVerify(@RequestBody @Valid YYPayApiReq2<AuthWithoutVerifyDirectParams> req)
			throws Throwable {

		logger.info(Log.op("AuthApiDirectController.directAuthConfirmWithoutCodeVerify").msg("独立鉴权请求参数").kv("req", req).toString());
		AuthWithoutVerifyDirectParams params = req.getParams();

		// 1.校验参数
		params.validate();

		AuthWithoutVerifyParams authParams = new AuthWithoutVerifyParams();
		BeanUtils.copyProperties(params, authParams);
		authParams.setMerchantCode(req.getMerchantCode());

		// 用户认证信息校验
		authService.checkUserAuth(authParams);

		// 持久订单信息, 订单幂等判断，如果订单已经出结果，找出原来信息
		AuthOrderPO authOrderPO = authService.saveAuthOderForWithout(authParams);

		// 订单幂等判断，如果订单已经出结果，则直接返回响应结果
		if (authOrderPO != null && (AuthStateEnum.SUCCESS.isValue(authOrderPO.getState()) || AuthStateEnum.FAIL.isValue(authOrderPO.getState()))) {
			return new YYFaxRsp<>(authOrderPO.getResultCode(), authOrderPO.getResultMsg(), null);
		}

		// 判断订单是否过期
		if (DateUtil.str2DateTime(authOrderPO.getExpireTime()).getTime() <= System.currentTimeMillis()) {
			return new YYFaxRsp<>(PayRspCodeEnum.COMMON_ERROR_BAD_REQUEST, "订单不存在/过期");
		}

		WithoutVerifyYYContent withoutVerifyYYContent = authService.authentication(authOrderPO, params);

		return new YYFaxRsp<>(withoutVerifyYYContent.getResultCode(), withoutVerifyYYContent.getResultMsg(), withoutVerifyYYContent.getResultMsg(),null);
	}
}
